package com.spark.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.spark.basecommon.api.R;
import com.spark.basecommon.entity.vo.LoginUserVO;
import com.spark.basecommon.exception.BusinessException;
import com.spark.userapi.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * @author fuqiang
 * @Description 用户认证实现类
 * @Date 2020/10/9
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        R<LoginUserVO> loginUserVOR = userFeign.getUserInfoByUserName(username);
        if(null == loginUserVOR || !loginUserVOR.getSuccess()){
            throw new BusinessException("根据"+ username +"未查询到用户");
        }
        LoginUserVO loginUserVO = loginUserVOR.getData();
        // 这里使用 username 存储整个用户信息 相当于 principal
        loginUserVO.setUsername(JSON.toJSONString(loginUserVO));
        return loginUserVOR.getData();
    }

    /**
     * 生成密码
     * @param args
     */
    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String admin = bCryptPasswordEncoder.encode("secret");
        System.out.println(admin);
    }
}
